# -*- coding: utf-8 -*-

import sqlite3
from datetime import date

from finance.db.DBStock import DBStock

class AnalyzeData(object):
	"""
	"""
	def __init__(self,vData):
		self.data = vData
		self.mini_len = 1
		self.key_index = 1

	def max_rise_range(self):
		begin = -1
		vRange = []
		for index in range(len(self.data) -1):
			cur = self.data[index][self.key_index]
			next = self.data[index+1][self.key_index]
			if next >= cur:
				if begin < 0:
					begin = index
				if index == (len(self.data) - 2):
					curRange = [self.data[begin][0],self.data[index+1][0],index+1 - begin,True]
					vRange.append(curRange)
					begin = -1
			elif begin >= 0:
				if (index - begin) >= self.mini_len:
					curRange = [self.data[begin][0],self.data[index][0],index - begin,False]
					vRange.append(curRange)
				begin = -1
		return vRange

	def max_fall_range(self):
		begin = -1
		vRange = []
		for index in range(len(self.data) -1):
			cur = self.data[index][self.key_index]
			next = self.data[index+1][self.key_index]
			if next <= cur:
				if begin < 0:
					begin = index
				if index == (len(self.data) -2 ):
					curRange = [self.data[begin][0],self.data[index+1][0],index+1 - begin,True]
					vRange.append(curRange)
					begin = -1
			elif begin >= 0:
				if (index - begin) >= self.mini_len:
					curRange = [self.data[begin][0],self.data[index][0],index - begin,False]
					vRange.append(curRange)
				begin = -1		
		return vRange

	def last_range(self):		
		riseRange = self.max_rise_range()
		if len(riseRange) > 0 and riseRange[-1][3]:
			if len(riseRange) == 1:
				return [riseRange[-1][2],0,True]
			return [riseRange[-1][2],riseRange[-2][2],True]		
		fallRange = self.max_fall_range()
		if len(fallRange) == 0:
			return None
		if len(fallRange) == 1:
			return [fallRange[-1][2],0,False]
		return [fallRange[-1][2],fallRange[-2][2],False]

	def last_reverse(self):		
		riseRange = self.max_rise_range()		
		fallRange = self.max_fall_range()
		if len(riseRange) < 1 or len(fallRange) < 1:
			return None

		if riseRange[-1][3]:
			return [riseRange[-1][2],fallRange[-1][2],True]
		else:
			return [fallRange[-1][2],riseRange[-1][2],False]


class AnalyzeStock(object):
	"""
	"""
	def __init__(self,db_path):
		self.db = sqlite3.connect(db_path)
		self.cur = self.db.cursor()
		self.db_stock = DBStock(self.db)
		self.codes = self.db_stock.fetch_hist_tb_name()


	def analyze_all_last_range(self):
		vLastRange = []

		for index in range(len(self.codes)):
			print "%s,%d/%d"%(self.his_tb[index],index,len(self.his_tb))
			lastStock = self.analyze_last_stock(self.codes[index])
			if lastStock is not None:
				vLastRange.append(lastStock)

		vLastRange = sorted(vLastRange,key=lambda v:float(v[2])/float(v[1]))
		for lRange in vLastRange:
			print lRange

	def analyze_last_stock(self,code):
		self.cur.execute('select date,lower from his_%s order by date'%(code))
		res = [row for row in self.cur.fetchall()]
		analyzeData = AnalyzeData(res)
		lastRange = analyzeData.last_reverse()
		if lastRange is None:
			return lastRange
		lastRange.insert(0,code)
		return lastRange

	def check_date(self,code,dt):
		sql = "select * from his_%s where date = '%s'"%(code,dt)
		self.cur.execute(sql)
		return len(self.cur.fetchall())

def main():
	analyze = AnalyzeStock("../finance.db")
	analyze.analyze_all_last_range()
	#ret = analyze.analyze_last_stock("his_002816")

if __name__ == '__main__':
	main()